package com.jwm.power.util;

import org.apache.logging.log4j.LogManager;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/websocket/{id}")
@Component
public class WebSocketServer {
    // 用于存储socketServer
    private static ConcurrentHashMap<String, WebSocketServer> webSocketSet = new ConcurrentHashMap<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private String id = "";

    /**
     * 连接建立成功
     * @param id
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam(value = "id") String id, Session session) {
        this.session = session;
        this.id = id;
        webSocketSet.put(id, this);
        System.out.println("用户"+id+"连接成功！当前人数："+webSocketSet.size());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            System.out.println("websocket IO异常");
        }

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam(value = "id") String id) {
        System.out.println("id:::"+id);
        webSocketSet.remove(id);  //从set中删除
        System.out.println("有一连接关闭！当前在线人数为"+webSocketSet.size());
    }

    /**
     * 异常
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    /**
     * 发送信息
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送指定用户消息
     * @param message
     * @param id
     * @throws IOException
     */
    public void sendtoUser(String message,String id) throws IOException {
        if (webSocketSet.get(id) != null) {
            webSocketSet.get(id).sendMessage(message);
        }
    }

    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) throws IOException {
        for (Map.Entry<String, WebSocketServer> sessionEntry : webSocketSet.entrySet()) {
            System.out.println(sessionEntry.getKey());
            sessionEntry.getValue().sendMessage(message);
        }
    }
}
